#include "events.h"

void events::starter(){
    if(SDL_Init( SDL_INIT_EVERYTHING ) == -1){
        exit(1);
    }
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
    if(!screen){
        exit(2);
    }
    if(TTF_Init() == -1){
        exit(3);
    }
    if(Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1){
		exit(4);
	}
    font = TTF_OpenFont("resources/sans.ttf", 48);
	if(!font) exit(5);
    digit = TTF_OpenFont("resources/digit.ttf",28);
	if(!digit) exit(6);
    hit = Mix_LoadWAV("resources/hit.wav");
	if(!hit) exit(7);
    SDL_WM_SetCaption("Pong tennis",NULL);
    int r=0,g=0,b=0xbf;
    events::CreateBackground(r,g,b);
}
void events::finisher(){
    Uint32 colorkey = SDL_MapRGB( message->format, 0, 0, 0 );
    SDL_SetColorKey( message, SDL_SRCCOLORKEY, colorkey );
    graphics::apply_surface(220,SCREEN_HEIGHT/2-40,message,screen);
    SDL_Flip(screen);
    SDL_FreeSurface(message);
    events::WaitForExit();
    Mix_FreeChunk(hit);
    TTF_CloseFont(font);
    SDL_FreeSurface(background);
    TTF_Quit();
    SDL_Quit();
    exit(0);
}
void events::pause(){
    while(1){
        while(SDL_PollEvent(&event)){
            if(event.type == SDL_QUIT) exit(0);
            if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_p) return;
        }
	SDL_Delay(1);
    }
}
void events::CLRSCR(){
    graphics::apply_surface(0,0,background,screen);
}

void events::WaitForExit(){
    while(1){
        while(SDL_PollEvent(&event)){
            if(event.type == SDL_QUIT) return;
            if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) return;
        }
	SDL_Delay(1);
    }
}
void events::Win(){
    message = TTF_RenderText_Shaded( font, "You win", textColor , bgColor);
    events::finisher();
}
void events::Lose(){
    message = TTF_RenderText_Shaded( font, "You lose", textColor , bgColor);
    events::finisher();
}

void events::CreateBackground(int r, int g, int b){
    SDL_Rect a = {0,0,SCREEN_WIDTH,SCREEN_HEIGHT};// a.x=0; a.y=0; a.w=SCREEN_WIDTH; a.h=SCREEN_HEIGHT;
    background = SDL_CreateRGBSurface(0,SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,0,0,0,0);
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, 0xff, 0xff, 0xff ));
    a = {10,10,50,460};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {580,10,50,460};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {70,10,500,120};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {70,350,500,120};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {70,140,245,200};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {325,140,245,200};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, r, g, b ));
    a = {0,238,640,4};
    SDL_FillRect(background,&a,SDL_MapRGB( background->format, 0, 0, 0 ));
}
